Custom Color Palettes in geom_imshow()¶

The cmap parameter in geom_imshow() controls how greyscale images are colorized.

It accepts either a colormap name (e.g., 'magma') or a list of color codes. When a list is provided, pixel values are binned across the given colors. For smoother gradients, you can use the palette(n) method on any color scale to generate a larger palette.

In [1]:
import numpy as np
import rasterio as ro

from lets_plot import *
LetsPlot.setup_html()
In [2]:
# Load Mount Rainier shaded relief (georeferenced tiff).
# Source: https://pugetsoundlidar.ess.washington.edu/lidardata/restricted/filegeodatabase/mtrainierNP/index.html
data = ro.open('./data/mount_rainier_shaded_relief.tif')
crs=data.crs
bounds=data.bounds
print("{}\n{}".format(crs, bounds))
EPSG:26910
BoundingBox(left=591605.8273623086, bottom=5187196.672708434, right=596902.2082595474, top=5190956.943133966)
In [3]:
# Get the first band as a 2D numpy array.
image = data.read(1)
type(image), np.shape(image)
Out[3]:
(numpy.ndarray, (1958, 2758))
In [4]:
extent = [bounds.left, bounds.right, bounds.bottom, bounds.top]

ggplot() + theme_void() + geom_imshow(image, extent=extent)
Out[4]:

Apply a Custom Palette¶

In [5]:
blue1 = '#97C3DC'
blue2 = '#1B63A5'

ggplot() + theme_void() + geom_imshow(
    image, 
    cmap=[blue2, blue1], # <-- Use palette containing just two colors
    extent=extent)
Out[5]:

Generate Palette Using scale.palette(n)¶

In [6]:
palette = (
    scale_color_gradient2(
        low=blue2, 
        mid='white', 
        high=blue1, 
        midpoint=0.5)       # <-- the midpoint should be in range -1..1 
    .palette(30)            # <-- generate 30 colors
)

ggplot() + theme_void() + geom_imshow(
    image, 
    cmap=palette, 
    extent=extent,
    cguide=guide_colorbar(  # <-- adjust the colorbar if needed
        title='shade',
        barwidth=8,
        barheight=300
    )
)
Out[6]: